package com.yunshu.yunshuapp.network;

import android.app.Activity;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.Toast;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.impl.ExternalTypeHandler;
import com.yunshu.yunshuapp.user.YSUser;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by zhouwenjie on 2016/12/31.
 */
public class YSRequest {

    public static final String BASE_URL =  "http://www.yunshutech.com" ; //"http://192.168.0.104:8080";//
    public static final String SEND_CODE = "/identifyingCodeService/getCode.action?";
    public static final String REGISTER = "/identifyingCodeService/validateCode.action?";
    public static final String LOGIN = "/loginService/appLogin.action?";
    public static final String FORGET_PASSWORD = "/userAuthorization/updatePasswordForApp.action?";
    public static final String UPLOAD_IMG = "/pictureService/uploadIcon.action?";
    public static final String UPLOAD_IMG2 = "/pictureService/uploadFile.action?";
    public static final String UPDATE_USER = "/userAuthorization/updateUserForApp.action?";
    public static final String ZIXUN_LIST = "/infomationService/getInfomationListByType.action?";
    public static final String ZIXUN_Banner = "/infomationService/getInfomationPicList.action?";
    public static final String ZIXUN_Detail = "/infomationService/toInfomationContent.action?id=";
    public static final String ZIXUN_Love = "/infomationService/updatePraiseNum.action?";
    public static final String HOMEPAGE = "/infomationService/getHomeContent.action?"; //   首页信息
    public static final String Kuaixun_Detail = "/newsFlashService/getNewsFlashById.action?";
    public static final String Kuaixun_LIST = "/newsFlashService/getNewsFlashListForApp.action?";
    public static final String Kuaixun_Channels = "/newsFlashService/getChannelListForApp.action?";
    public static final String Kuaixun_Share = "/newsFlashService/toNewsFlashContent.action?";
    public static final String KUAIXUN_Love =  "/newsFlashService/updatePraiseNum.action?";
    public static final String TONGXUNLU_LIST = "/companyAddressListService/getCompanyAddressList.action?";
    public static final String TONGXUNLU_DETAIL = "/companyAddressListService/getCompanyAddressListById.action?";
    public static final String TONGXUNLU_DETAIL_PRICE = "/companyAddressListService/toPriceStrategy.action?requestType=app";
    public static final String TONGXUNLU_DETAIL_PRODUCT = "/companyAddressListService/toProductContent.action?requestType=app";
    public static final String XIANHUO_LIST = "/spotGoodsService/getCompanyAddressList.action?" ;
    public static final String XIANHUO_MINE_LIST = "/spotGoodsService/getSpotGoodsListByUserId.action?" ;
    public static final String XIANHUO_POST = "/spotGoodsService/insertSpotGoodsForApp.action?";
    public static final String XIANHUO_TEMPLATE_LIST = "/spotGoodsService/getSpotGoodsTempletListByUserId.action?";
    public static final String XIANHUO_TEMPLATE_ADD = "/spotGoodsService/insertSpotGoodsTempletForApp.action?";
    public static final String XIANHUO_TEMPLATE_DELETE = "/spotGoodsService/deleteSpotGoodsTempletForApp.action?";
    public static final String AGREEMENT = "/云数智惠APP应用软件许可及服务协议.html";

    public static final String checkUpdate = "/userAuthorization/getVersion.action?";

    public static final String Feedback = "/questionService/insertQuestion.action?";
    public static final String XIANHUO_UPDATE = "/spotGoodsService/updateSpotGoodsForApp.action?";

    public static final String PushChannelBind = "/userAuthorization/bindBpushChannelId.action?";
    /**
     *  用来展示对话框
     */
    private final Activity activity;
    private boolean isCompleted;

    public static final int REQUEST_OK = 1;
    private Request request;

    public YSRequest(Activity activity1){
        activity = activity1;
        isCompleted = true;
    }

    public boolean getIsCompleted(){
        return isCompleted;
    }

    public void GET(String url, String params, final YSCallback yscallback){
        isCompleted = false;
        String defaultParams = "requestType=app&";
        if (YSUser.instance().getToken() != null){
            defaultParams += "token=" + YSUser.instance().getToken() + "&";
        }
        url = BASE_URL + url + defaultParams + params;

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
//创建一个Request
        request = new Request.Builder()
                .url(url)
                .build();
//new call
        Call call = mOkHttpClient.newCall(request);
//请求加入调度
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {

                String ex = e.getMessage();
                alert("网络异常，请稍后重试");
                yscallback.onResponse(-1,null);
                isCompleted = true;

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseString =  response.body().string();
                Log.i("onResponse:", responseString );

                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    JsonNode jsonNode = objectMapper.readTree(responseString);
                    int code = jsonNode.get("code").asInt();
                    if (jsonNode.get("token") != null) {
                        YSUser.instance().setToken(jsonNode.get("token").asText());
                    }
                    if (code == 1) {
                        JsonNode resultNode = null;
                        if (jsonNode.get("result") != null && jsonNode.get("result").isTextual()) {
                            String jsonStr = jsonNode.get("result").textValue();
                            resultNode = objectMapper.readTree(jsonStr);
                        } else {
                            resultNode = jsonNode.get("result");
                        }
                        yscallback.onResponse(1, resultNode);

                    } else {
                        String msg = jsonNode.get("msg").asText("服务器繁忙");
                        alert(msg);
                        yscallback.onResponse(code, null);
                    }
                }catch (Exception e){
                    yscallback.onResponse(-1, null);
                }
                isCompleted = true;
            }


        });
    }

    public void POST(String url, Map<String ,String> params, final YSCallback yscallback){
        String defaultParams = "requestType=app&";
        if (YSUser.instance().getToken() != null){
            defaultParams += "token=" + YSUser.instance().getToken() + "&";
        }
        url = BASE_URL + url + defaultParams;

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("requestType","app");
        if (YSUser.instance().getToken() != null) {
            builder.addFormDataPart("token", YSUser.instance().getToken());
        }
        for (String key : params.keySet()){
            if (params.get(key) != null)
                builder.addFormDataPart(key,params.get(key));
        }

        MultipartBody requestBody = builder.build();


//创建一个Request
        request = new Request.Builder()
                .url(url).post(requestBody)
                .build();
//new call
        Call call = mOkHttpClient.newCall(request);
//请求加入调度
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {

                String ex = e.getMessage();
                alert("网络异常，请稍后重试");
                yscallback.onResponse(-1,null);

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseString =  response.body().string();
                Log.i("onResponse:", responseString );

                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = null;
                try {
                    jsonNode = objectMapper.readTree(responseString);
                }catch (Exception e){
                        e.printStackTrace();
                    alert("服务器繁忙");
                    yscallback.onResponse(-1,null);
                    return;
                }
                int code = jsonNode.get("code").asInt();
                if (jsonNode.get("token") != null){
                    YSUser.instance().setToken(jsonNode.get("token").asText());
                }
                if ( code == 1){
                    yscallback.onResponse(1, jsonNode.get("result"));

                }else {
                    String msg = jsonNode.get("msg").asText("服务器繁忙");
                    alert(msg);
                    yscallback.onResponse(code,null);
                }

            }

        });
    }

    public void uploadImg(String imagePath, Bitmap newimg, final YSCallback yscallback) {

        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f=new File(imagePath);
        if (f!=null) {

            MediaType mediaType = MediaType.parse("image/jpg");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            newimg.compress(Bitmap.CompressFormat.JPEG, 70, bos);
            byte[] data = bos.toByteArray();
            builder.addFormDataPart("img", f.getName(), RequestBody.create(mediaType, data));
        }
        //添加其它信息
        builder.addFormDataPart("requestType","app");
        if (YSUser.instance().getToken() != null) {
            builder.addFormDataPart("token", YSUser.instance().getToken());
        }
//        builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude());
//        builder.addFormDataPart("name",SharedInfoUtils.getUserName());


        MultipartBody requestBody = builder.build();

        String defaultParams = "requestType=app&";
        if (YSUser.instance().getToken() != null){
            defaultParams += "token=" + YSUser.instance().getToken() + "&";
        }
        String url = BASE_URL + UPLOAD_IMG + defaultParams;

        //构建请求
        request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .build();

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                yscallback.onResponse(-1,null);
                alert("上传失败," + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String responseString =  response.body().string();
                Log.i("onResponse:", responseString );

                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(responseString);
                int code = jsonNode.get("code").asInt();

                if (jsonNode.get("token") != null){
                    YSUser.instance().setToken(jsonNode.get("token").asText());
                }
                if ( code == 1){
                    yscallback.onResponse(1, jsonNode.get("result"));

                }else {
                    String msg = jsonNode.get("msg").asText("服务器繁忙");
                    alert(msg);
                    yscallback.onResponse(code,null);
                }
            }
        });

    }

    public void uploadImg2(String imagePath, Bitmap newimg, final YSCallback yscallback) {

        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        File f=new File(imagePath);
        if (f!=null) {

            MediaType mediaType = MediaType.parse("image/jpg");
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            newimg.compress(Bitmap.CompressFormat.JPEG, 80, bos);
            byte[] data = bos.toByteArray();
            builder.addFormDataPart("img", f.getName(), RequestBody.create(mediaType, data));
        }
        //添加其它信息
        builder.addFormDataPart("requestType","app");
        if (YSUser.instance().getToken() != null) {
            builder.addFormDataPart("token", YSUser.instance().getToken());
        }
//        builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude());
//        builder.addFormDataPart("name",SharedInfoUtils.getUserName());


        MultipartBody requestBody = builder.build();

        String defaultParams = "requestType=app&";
        if (YSUser.instance().getToken() != null){
            defaultParams += "token=" + YSUser.instance().getToken() + "&";
        }
        String url = BASE_URL + UPLOAD_IMG2 + defaultParams;

        //构建请求
        request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .build();

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                yscallback.onResponse(-1,null);
                alert("上传失败," + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String responseString =  response.body().string();
                Log.i("onResponse:", responseString );

                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(responseString);
                int code = jsonNode.get("code").asInt();

                if (jsonNode.get("token") != null){
                    YSUser.instance().setToken(jsonNode.get("token").asText());
                }
                if ( code == 1){
                    yscallback.onResponse(1, jsonNode.get("result"));

                }else {
                    String msg = jsonNode.get("msg").asText("服务器繁忙");
                    alert(msg);
                    yscallback.onResponse(code,null);
                }
            }
        });

    }

    private void alert(final String s) {
        if (activity == null)
            return;

        activity.runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                Toast.makeText(activity.getApplicationContext(), s,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}
